<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Comments/classes/PhpFox_ComponentList.class.php, $Author:  $ */



/** Component for viewing comments
 *
 * @version $Id: PhpFox_ComponentList.class.php 297 2008-02-07 15:05:58Z phpfoxsv $
 * @package module.comments
 */
class PhpFox_Mod_Comments_ComponentList extends BaseComponent
{
    function process()
    {
    	$oAccountService = &App::getModuleService('Account', 'Account');
        $oCommentItem = &$this->_oModule->getItem('Comment');
        /* @var $oCommentItem PhpFox_Mod_Comments_ItemComment */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oTpl = &$this->_oModule->getTemplate();
        $oReq = &App::getRequest();
        $oUrl = &App::getUrl();
        App::loadClass('Pager');
        App::loadClass('Text');
        $oText = &new Text();

        $sUser = $oSecurityService->getCurrentUserLogin();
        $aTypes = array
        (
            'blog',
            'gallery',
            'account',
            'music_album',
            'music_song',
            'video',
        );
        $sType = $this->_aParams['type'];
        if (!in_array($sType, $aTypes))
        {
            return '';
        }
        $mId = $this->getParam('id');
        if (!$mId)
        {
            if ($sType == 'account')
            {
                $mId = $oReq->get('name');
            }
            else
            {
                $mId = $oReq->getInt('id');
            }
        }
        if (!$mId)
        {
            return '';
        }
        $bAdmin = $oSecurityService->isStaff();
        $bCan = false;
        switch ($sType)
        {
            case 'blog':
                if (!$oSecurityService->checkPerm('blog', array('read_only', 'full'), 0))
                {
                    return '';
                }
                if ($oSecurityService->checkPerm('blog', array('full'), 0))
                {
                    $bCan = true;
                }
                break;
            case 'gallery':
                if (!$oSecurityService->checkPerm('gallery', array('read_only', 'full'), 0))
                {
                    return '';
                }
                if ($oSecurityService->checkPerm('gallery', array('full'), 0))
                {
                    $bCan = true;
                }
                break;
            case 'account':
                if (!$oSecurityService->checkPerm('profile', array('read_only', 'full'), 0))
                {
                    return '';
                }
                if ($oSecurityService->checkPerm('profile', array('full'), 0))
                {
                    $bCan = true;
                }
                break;
            case 'music_album':
            case 'music_song':
                if (!$oSecurityService->checkPerm('music', array('read_only', 'full'), 0))
                {
                    return '';
                }
                if ($oSecurityService->checkPerm('music', array('full'), 0))
                {
                    $bCan = true;
                }
                break;
        }
        if ($iCommentId = $oReq->getInt('cdelete'))
        {
        	if ( $sType == 'video' )
			{
	  			$aItem = $this->oDatabase->getRow("SELECT cm_id, cm_userid, cm_mainid FROM ". App::getT('videos_comments') ." WHERE cm_id = '". $iCommentId ."'");
	  			if (isset($aItem['cm_userid']) && (($aItem['cm_userid'] == App::getUser('id')) || $bAdmin))
            	{           		
            		$aVideoItem = $this->oDatabase->getRow("SELECT comments FROM ". App::getT('videos') ." WHERE vid_id = '". $aItem['cm_mainid'] ."'");

            		$iNewCount = ($aVideoItem['comments']-1);

            		$this->oDatabase->_delete(App::getT('videos_comments'), "cm_id = '". $iCommentId ."'");
            		$this->oDatabase->update(App::getT('videos'), array('comments' => $iNewCount), "vid_id = '". $aItem['cm_mainid'] ."'");
            		$oAccountService->changeUserInfo($oAccountService->getById($aItem['cm_userid']), 'comment', -1, ($aItem['cm_userid'] == App::getUser('id') ? true : false));
            		
            		$this->oDatabase->_delete(App::getT('mail_alert'), "type = '6' AND item = '" . $mId . "' AND c_id = '". $iCommentId ."' AND user_id = '" . $aItem['cm_userid'] . "'");
				}
			}
			else
			{
        		// Get the comment details
        		$aItem = $this->oDatabase->getRow("SELECT userid, itemid FROM ". App::getT('comments') ." WHERE cid = '". $iCommentId ."'");

        	    if (($aItem['userid'] == App::getUser('id')) || $bAdmin || ($sType == 'account' && $aItem['itemid'] == App::getUser('id')))
        	    {
        	    	// Load comment Service
        	    	$oCommentService = &$this->_oModule->getService('Comment');                 	
        	    	
					// Lets delete the comment
	                $oCommentService->onDelete($iCommentId);

	                if ( $sType == 'account' )
	                {
	                	// Update how many comments this specific user has
						$iNewCount = $oCommentService->updateCounts('user', 'c_comments', "id = '". $aItem['itemid'] ."'", App::getParam('aCommentId',$sType), $aItem['itemid']);

	                }
	                elseif ( $sType == 'gallery' )
	                {
	                	$oCommentService->updateCounts('main', 'comment', "id = '". $aItem['itemid'] ."'", App::getParam('aCommentId',$sType), $aItem['itemid']);
	                }
	                elseif ( $sType == 'blog' )
	                {
	                	$oCommentService->updateCounts('journal', 'comment', "id = '". $aItem['itemid'] ."'", App::getParam('aCommentId',$sType), $aItem['itemid']);
	                }
	            }
	            $oUrl->clearParams('cdelete');
	            $this->oDatabase->_delete(App::getT('mail_alert'), "type = '" . App::getParam('aCommentId',$sType) . "' AND item = '" . $mId . "' AND c_id = '". $iCommentId ."' AND user_id = '" . $aItem['userid'] . "'");
	            App::forward($oUrl->getUrl(), App::format('Mod_Comments.comment_deleted'), 'message', App::getPageName(), 'comment');
            }
        }
        $aCond = array();
        $iPageSize = App::getParam('total_page_comments');

        if ( !$iPageSize )
        {
        	return '';
        }

        switch ($sType)
        {
            case 'blog':
                $aCond['main'] = '= "journal"';
                $aCond['cid'] = '= '.$mId;
                break;
            case 'account':
                $aCond['main'] = '= "gb"';
                $aCond['gbuser'] = '= "'.$mId.'"';
                if (!$this->getParam('is_guestbook'))
                {
                    $iPageSize = App::getParam('profile_gb_total');
                    if ( !$iPageSize )
        			{
        				return '';
        			}
                }
                break;
            case 'gallery':
                $aCond['main'] = '= '.$mId;
                break;
            case 'music_song':
                $aCond['main'] = '= "msong"';
                $aCond['cid'] = '= '.$mId;
                break;
            case 'music_album':
                $aCond['main'] = '= "malbum"';
                $aCond['cid'] = '= '.$mId;
                break;
        }

        if (!$iPageSize)
        {
            $iPage = 0;
            $oUrl->clearParams('page');
        }
        else
        {
            $iPage = ($this->getParam('page') ? $this->getParam('page')  : $oReq->getInt('page', 1));
        }
        $sSort = 'time DESC';

		if ( $sType == 'video' )
		{
			if ( $iTempCount = $this->getParam('totalCount') )
			{
				$iCnt = $iTempCount;
				if(isset($iNewCount))
				{
					$iCnt = $iNewCount;
				}
			}
			else
			{
				$aItemsTotal = $this->oDatabase->getRow("SELECT COUNT(*) AS count FROM ". App::getT('videos_comments') ."".
					" WHERE cm_mainid = '". $mId ."' ".
					" ");
				$iCnt = $aItemsTotal['count'];
			}
        
			$bCan = true;

			$aItems = $oCommentItem->getListing("SELECT cm_id AS cid, cm_userid, cm_text AS text, cm_time AS time, user.user, user.id AS itemid FROM
	  			". App::getT('videos_comments') ." AS comment
	  			JOIN ". App::getT('user') ." AS user ON(comment.cm_userid = user.id)
	  			WHERE cm_mainid = '". $mId ."'
	  			ORDER BY cm_time DESC", $iCnt, $iPage, $iPageSize);

			$oTpl->assign(array
			(
				'bUseAjaxLinks' => true,
				'sCmtType' => 'video',
				'totalCount' => $iCnt,
			));

		}
		else
		{
			if ( $iTempCount = $this->getParam('totalCount') )
			{
				$iCnt = $iTempCount;
			}
			else
			{
				$aItemsTotal = $this->oDatabase->getRow("
					SELECT COUNT(*) AS count FROM ". App::getT('comments') ."".
					" WHERE typeid = '". App::getParam('aCommentId',$sType) ."' AND itemid = '". $mId ."' ".
					" ");
				$iCnt = $aItemsTotal['count'];
			}


			if ( $iDoLimit = $this->getParam('doLimit') )
			{
				$aItems = $this->oDatabase->getRows("
					SELECT 
						c.cid, c.itemid, c.text, c.time, u.user 
					FROM ". App::getT('comments') ." AS c
						JOIN ". App::getT('user') ." AS u ON(c.userid = u.id)
					WHERE c.typeid = '". App::getParam('aCommentId',$sType) ."' AND c.itemid = '". $mId ."'
					ORDER BY c.time DESC LIMIT 0,". $iDoLimit ."
				");
		        $oTpl->assign(array(
        			'iDoLimit' => ($iDoLimit > $iCnt ? $iCnt : $iDoLimit),
        			'sUser' => $oReq->get('name')
        		));
			}
			else
			{
				$aItems = $oCommentItem->getListing("
					SELECT c.cid, c.itemid, c.text, c.time, u.user FROM ". App::getT('comments') ." AS c ".
					" JOIN ". App::getT('user') ." AS u ON(c.userid = u.id) ".
					" WHERE c.typeid = '". App::getParam('aCommentId',$sType) ."' AND c.itemid = '". $mId ."'".
					" ORDER BY c.time DESC", $iCnt, $iPage, $iPageSize);
			}
		}

        if ($sType == 'account')
        {
            if (isset($this->_aParams['gbHtml']) && $this->_aParams['gbHtml'] && App::getSetting('allow_html'))
            {
                foreach ($aItems as $iKey => $aItem)
                {
                    $aItems[$iKey]['text'] = $oText->parseText($aItem['text'], true);
                }
                $oTpl->assign('bDontProcess', true);
            }
        }

		$bOwner = false;
        if ($iCnt AND isset($aItems[0]['itemid']))
        {
            $bOwner = ($aItems[0]['itemid'] == App::getUser('id')) ? true : false;
        }

        foreach ($aItems as $iKey => $aItem)
        {
            $bAuthor = false;
            if ($aItem['user'] == $sUser)
            {
                $bAuthor = true;
            }
            $aItems[$iKey]['can_delete'] = ((($bOwner || $bAuthor) && $bCan) || $bAdmin);
        }

		if ( empty($iDoLimit) )
		{
    		$oPager = &new Pager($iCnt, $iPage, $iPageSize);
        	$iFrom = $oPager->getOffset($iPage, $iPageSize);
        	$iTo = (($iFrom + $iPageSize) > $iCnt) ? $iCnt : ($iFrom + $iPageSize);
        	$oTpl->assign(array(
        		'aPaging'          => ($iCnt && $iPageSize) ? $oPager->getInfo($oUrl) : '',
        		'iFrom'            => ($iCnt) ? ($iFrom + 1) : 0,
        		'iTo'              => $iTo,
        		'iPageSize'        => $iPageSize
        	));
        }

		$oTpl->assignSrc('aItems', $aItems);
        $oTpl->assign(array(
        	'iCnt'             => $iCnt,
        	'sUImageUrl'       => App::getParam('user.pic.url'),
            'aErrors'          => $this->getErrors(),
            'bShowImages'      => App::getSetting('show_comment_images'),
        	'bUseAjax'  	   => $this->getParam('useajax')
        ));
        return $oTpl->fetch('List.html');
    }
}
?>